// 多标签页状态管理
import { history } from '@umijs/max';
import { useCallback, useState } from 'react';

export interface TabItem {
  key: string; // 路由路径
  title: string; // 标签页标题
  closable: boolean; // 是否可关闭
}

const useTabs = () => {
  // 初始化时添加首页
  const [tabs, setTabs] = useState<TabItem[]>([
    { key: '/home', title: '首页', closable: false },
  ]);
  const [activeKey, setActiveKey] = useState<string>('/home');

  // 添加标签页
  const addTab = useCallback((tab: TabItem) => {
    setTabs((prevTabs) => {
      // 检查标签页是否已存在
      const exists = prevTabs.some((item) => item.key === tab.key);
      if (!exists) {
        return [...prevTabs, tab];
      }
      return prevTabs;
    });
    setActiveKey(tab.key);
  }, []);

  // 删除标签页
  const removeTab = useCallback(
    (targetKey: string) => {
      setTabs((prevTabs) => {
        const newTabs = prevTabs.filter((tab) => tab.key !== targetKey);

        // 如果删除的是当前激活的标签页，则激活相邻的标签页
        if (targetKey === activeKey) {
          const index = prevTabs.findIndex((tab) => tab.key === targetKey);
          const newActiveKey =
            index > 0
              ? prevTabs[index - 1].key
              : newTabs.length > 0
              ? newTabs[0].key
              : '/home';

          setActiveKey(newActiveKey);
          history.push(newActiveKey);
        }

        return newTabs;
      });
    },
    [activeKey],
  );

  // 切换标签页
  const changeTab = useCallback((key: string) => {
    setActiveKey(key);
    history.push(key);
  }, []);

  // 关闭其他标签页
  const closeOtherTabs = useCallback((currentKey: string) => {
    setTabs((prevTabs) => {
      const newTabs = prevTabs.filter(
        (tab) => tab.key === currentKey || !tab.closable,
      );
      return newTabs;
    });
    setActiveKey(currentKey);
    history.push(currentKey);
  }, []);

  // 关闭所有标签页（除了不可关闭的）
  const closeAllTabs = useCallback(() => {
    setTabs((prevTabs) => {
      const newTabs = prevTabs.filter((tab) => !tab.closable);
      const homeTab = newTabs.find((tab) => tab.key === '/home');
      const newActiveKey = homeTab ? homeTab.key : newTabs[0]?.key || '/home';
      setActiveKey(newActiveKey);
      history.push(newActiveKey);
      return newTabs;
    });
  }, []);

  // 刷新当前标签页
  const refreshTab = useCallback(() => {
    // 触发页面刷新，可以通过重新加载当前路由实现
    window.location.reload();
  }, []);

  return {
    tabs,
    activeKey,
    addTab,
    removeTab,
    changeTab,
    closeOtherTabs,
    closeAllTabs,
    refreshTab,
    setActiveKey,
  };
};

export default useTabs;
